/**
 * 数据表操作
 * 
 * @author 迟胜强
 * @date 2017-3-5
 * @info 当前类之用于快速生成SQL语句,如果需要配合其他类使用
 */

package aorey.database;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Table {

	public String tablename = null;
	public HashMap<String, Object> fields = null;

	public Table(String tableName) {
		this.tablename = tableName;
		this.fields = new HashMap<String, Object>();
	}

	// public void setField(String name,Field field)
	// {
	// this.fields.put(name,field);
	// }

	public void setField(String name, Object field) {
		this.fields.put(name, field);
	}

	@SuppressWarnings("rawtypes")
	public String insert() {
		StringBuilder result = new StringBuilder();
		StringBuilder fields = new StringBuilder();
		StringBuilder values = new StringBuilder();
		result.append("insert into " + this.tablename);
		Map map = this.fields;
		int i = 0;
		Iterator iter = map.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			if (i > 0) {
				values.append(",");
				fields.append(",");
			}
			String key = (String) entry.getKey();
			// Field val = (Field) entry.getValue();
			Object val = entry.getValue();
			fields.append(key);
			values.append("'" + val.toString() + "'");
			i++;
		}
		result.append("(" + fields.toString() + ") values(" + values.toString() + ")");
		this.fields.clear();
		return result.toString();
	}

	@SuppressWarnings("rawtypes")
	public String update(String find) {

		StringBuilder result = new StringBuilder();
		StringBuilder fields = new StringBuilder();
		result.append("update " + this.tablename);
		Map map = this.fields;
		int i = 0;
		Iterator iter = map.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			if (i > 0) {
				fields.append(",");
			}
			String key = (String) entry.getKey();
			Object val = entry.getValue();
			fields.append(key + "='" + val.toString() + "'");
			i++;
		}
		result.append(" set " + fields.toString());

		if (find != null && find != "") {
			result.append(" where " + find);
		}
		this.fields.clear();
		return result.toString();
	}

	public void clear() {
		this.fields.clear();
	}
}
